package com.yao.component.cityselector;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerBase;
import com.yao.component.cityselector.R;
import com.yao.component.cityselector.cityutils.City;
import com.yao.component.cityselector.cityutils.DBHelper;
import com.yao.component.cityselector.cityutils.DatabaseHelper;
import com.yao.component.cityselector.cityutils.MyLetterListView;
import com.yao.component.cityselector.cityutils.PingYinUtil;
import com.yao.sdk.cache.filestore.FileStoreProxy;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

public class CityListActivity extends Activity implements View.OnClickListener, AbsListView.OnScrollListener, AMapLocationListener {

    private BaseAdapter adapter;
    private ResultListAdapter resultListAdapter;
    private ListView personList;
    private ListView resultList;
    private TextView overlay; // 对话框首字母textview
    private MyLetterListView letterListView; // A-Z listview
    private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
    private String[] sections;// 存放存在的汉语拼音首字母
    private Handler handler;
    private Handler handler1 = new Handler();
    private OverlayThread overlayThread; // 显示首字母对话框
    private ArrayList<City> allCity_lists; // 所有城市列表
    private ArrayList<City> city_lists;// 城市列表
    private ArrayList<City> city_hot;
    private ArrayList<City> city_result;
    private ArrayList<String> city_history;
    private EditText sh;
    private TextView tv_noresult;
    private TextView province;
    private TextView historycityone;
    private TextView historycitytwo;
    private TextView historycitythree;
    private TextView classify;
    private TextView city;
    private DatabaseHelper helper;
    private String cityname;
    private AMapLocation aMapLocation;// 用于判断定位超时
    private TextView list_city;
    private SharedPreferences sp;
    private SharedPreferences sp2;
    private String history;
    private String[] strArray;
    private String cityName;
    private WindowManager windowManager;
    private WindowManager.LayoutParams lp;
    private AMapLocationClientOption locationOption;
    private LocationManagerBase locationClient;
    private TextView top_tv_title;
    private TextView top_left_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_list);

        sp2 = getSharedPreferences("historycity0", Activity.MODE_PRIVATE);
        history = sp2.getString("history", "");
        cityname = FileStoreProxy.getString("cityname");
        strArray = history.split(",");
        Log.e("history", history.toString());
        top_tv_title = (TextView) findViewById(R.id.top_tv_title);
        top_tv_title.setText("城市列表");
        top_left_tv = (TextView) findViewById(R.id.top_left_tv);
        top_left_tv.setText("取消");
        top_left_tv.setOnClickListener(this);
        personList = (ListView) findViewById(R.id.list_view);
        allCity_lists = new ArrayList<City>();
        city_hot = new ArrayList<City>();
        city_result = new ArrayList<City>();
        city_history = new ArrayList<String>();
        resultList = (ListView) findViewById(R.id.search_result);
        sh = (EditText) findViewById(R.id.city_search_edittext);
        tv_noresult = (TextView) findViewById(R.id.tv_noresult);
        helper = new DatabaseHelper(this);
        sh.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString() == null || "".equals(s.toString())) {
                    letterListView.setVisibility(View.VISIBLE);
                    personList.setVisibility(View.VISIBLE);
                    resultList.setVisibility(View.GONE);
                    tv_noresult.setVisibility(View.GONE);
                } else {
                    city_result.clear();
                    letterListView.setVisibility(View.GONE);
                    personList.setVisibility(View.GONE);
                    getResultCityList(s.toString());
                    if (city_result.size() <= 0) {
                        tv_noresult.setVisibility(View.VISIBLE);
                        resultList.setVisibility(View.GONE);
                    } else {
                        tv_noresult.setVisibility(View.GONE);
                        resultList.setVisibility(View.VISIBLE);
                        resultListAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        letterListView = (MyLetterListView) findViewById(R.id.MyLetterListView01);
        letterListView
                .setOnTouchingLetterChangedListener(new LetterListViewListener());
        alphaIndexer = new HashMap<String, Integer>();
        handler = new Handler();
        overlayThread = new OverlayThread();
        personList.setAdapter(adapter);
        personList.setOnScrollListener(this);
        resultListAdapter = new ResultListAdapter(this, city_result);
        resultList.setAdapter(resultListAdapter);
        resultList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                sp = getSharedPreferences("historycity0", Activity.MODE_PRIVATE);
                if (strArray.length < 2) {
                    history = city_result.get(position).getName() + "," + history;
                } else {
                    history = city_result.get(position).getName() + "," + history;
                    int i = history.lastIndexOf(",");
                    history = history.substring(0, i);
                }
                Log.e("history", history.toString());
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("history", history);
                edit.commit();
                FileStoreProxy.setValue("cityname", city_result.get(position).getName());


                Toast.makeText(CityListActivity.this, city_result.get(position).getName(), Toast.LENGTH_SHORT).show();
                Intent date = new Intent();
                date.putExtra("city", city_result.get(position).getName());
                setResult(ResultCode.DetialCode, date);
                finish();
            }
        });
        initOverlay();
        cityInit();
        hotCityInit();
        hisCityInit();
        setAdapter(allCity_lists, city_hot, city_history);

        personList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position >= 4) {

                    sp = getSharedPreferences("historycity0", Activity.MODE_PRIVATE);
                    if (strArray.length < 2) {
                        history = allCity_lists.get(position).getName() + "," + history;
                    } else {
                        history = allCity_lists.get(position).getName() + "," + history;
                        int i = history.lastIndexOf(",");
                        history = history.substring(0, i);
                    }
                    Log.e("history", history.toString());
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("history", history);
                    edit.commit();
                    FileStoreProxy.setValue("cityname", allCity_lists.get(position).getName());


                    Toast.makeText(CityListActivity.this, allCity_lists.get(position).getName(), Toast.LENGTH_SHORT).show();
                    Intent date = new Intent();
                    date.putExtra("city", allCity_lists.get(position).getName());
                    setResult(ResultCode.DetialCode, date);
                    finish();
                }
            }
        });
//        location();
    }

    private void location() {
        locationClient = new AMapLocationClient(getApplicationContext());
        locationOption = new AMapLocationClientOption();
        //设置为单次定位
        locationOption.setOnceLocation(true);
        // 设置定位模式为低功耗模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        // 设置定位监听
        locationClient.setLocationListener(this);
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
        mHandler.sendEmptyMessage(Util.MSG_LOCATION_START);
    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case Util.MSG_LOCATION_START:
                    province.setText("正在定位...");
                    break;
                //定位完成
                case Util.MSG_LOCATION_FINISH:
                    AMapLocation loc = (AMapLocation) msg.obj;
                    String province2 = loc.getProvince();
                    cityName = loc.getCity();
                    String district2 = loc.getDistrict();
                    province.setText(province2);
                    city.setText(cityName);
                    classify.setText(district2);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    // 定位监听
    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (null != loc) {
            Message msg = mHandler.obtainMessage();
            msg.obj = loc;
            msg.what = Util.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }
    }

    private void cityInit() {
        City city = new City("#", "0"); // 当前定位城市
        allCity_lists.add(city);
        city = new City("#", "1"); // 最近访问的城市
        allCity_lists.add(city);
        city = new City("#", "2"); // 热门城市
        allCity_lists.add(city);
        city = new City("#", "3"); // 全部城市
        allCity_lists.add(city);
        city_lists = getCityList();
        allCity_lists.addAll(city_lists);
    }

    /**
     * 热门城市
     */
    public void hotCityInit() {
        City city = new City("上海", "2");
        city_hot.add(city);
        city = new City("北京", "2");
        city_hot.add(city);
        city = new City("广州", "2");
        city_hot.add(city);
        city = new City("深圳", "2");
        city_hot.add(city);
        city = new City("西安", "2");
        city_hot.add(city);
        city = new City("杭州", "2");
        city_hot.add(city);
    }

    private void hisCityInit() {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "select * from recentcity order by date desc limit 0, 3", null);
        while (cursor.moveToNext()) {
            city_history.add(cursor.getString(1));
        }
        cursor.close();
        db.close();
    }

    @SuppressWarnings("unchecked")
    private ArrayList<City> getCityList() {
        DBHelper dbHelper = new DBHelper(this);
        ArrayList<City> list = new ArrayList<City>();
        try {
            dbHelper.createDataBase();
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor cursor = db.rawQuery("select * from city", null);
            City city;
            while (cursor.moveToNext()) {
                city = new City(cursor.getString(1), cursor.getString(2));
                list.add(city);
            }
            cursor.close();
            db.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(list, comparator);
        return list;
    }

    @SuppressWarnings("unchecked")
    private void getResultCityList(String keyword) {
        DBHelper dbHelper = new DBHelper(this);
        try {
            dbHelper.createDataBase();
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor cursor = db.rawQuery(
                    "select * from city where name like \"%" + keyword
                            + "%\" or pinyin like \"%" + keyword + "%\"", null);
            City city;
            Log.e("info", "length = " + cursor.getCount());
            while (cursor.moveToNext()) {
                city = new City(cursor.getString(1), cursor.getString(2));
                city_result.add(city);
            }
            cursor.close();
            db.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(city_result, comparator);
    }

    /**
     * a-z排序
     */
    @SuppressWarnings("rawtypes")
    Comparator comparator = new Comparator<City>() {
        @Override
        public int compare(City lhs, City rhs) {
            String a = lhs.getPinyi().substring(0, 1);
            String b = rhs.getPinyi().substring(0, 1);
            int flag = a.compareTo(b);
            if (flag == 0) {
                return a.compareTo(b);
            } else {
                return flag;
            }
        }
    };

    private void setAdapter(List<City> list, List<City> hotList,
                            List<String> hisCity) {
        adapter = new ListAdapter(this, list, hotList, hisCity);
        personList.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        windowManager.removeView(overlay);
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    private class ResultListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private ArrayList<City> results = new ArrayList<City>();

        public ResultListAdapter(Context context, ArrayList<City> results) {
            inflater = LayoutInflater.from(context);
            this.results = results;
        }

        @Override
        public int getCount() {
            return results.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_item, null);
                viewHolder = new ViewHolder();
                viewHolder.name = (TextView) convertView
                        .findViewById(R.id.name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.name.setText(results.get(position).getName());
            return convertView;
        }

        class ViewHolder {
            TextView name;
        }
    }

    public class ListAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;
        private List<City> list;
        private List<City> hotList;
        private List<String> hisCity;
        final int VIEW_TYPE = 5;

        public ListAdapter(Context context, List<City> list,
                           List<City> hotList, List<String> hisCity) {
            this.inflater = LayoutInflater.from(context);
            this.list = list;
            this.context = context;
            this.hotList = hotList;
            this.hisCity = hisCity;
            alphaIndexer = new HashMap<String, Integer>();
            sections = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                // 当前汉语拼音首字母
                String currentStr = getAlpha(list.get(i).getPinyi());
                // 上一个汉语拼音首字母，如果不存在为" "
                String previewStr = (i - 1) >= 0 ? getAlpha(list.get(i - 1)
                        .getPinyi()) : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = getAlpha(list.get(i).getPinyi());
                    alphaIndexer.put(name, i);
                    sections[i] = name;
                }
            }
        }

        @Override
        public int getViewTypeCount() {
            return VIEW_TYPE;
        }

        @Override
        public int getItemViewType(int position) {
            return position < 4 ? position : 4;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        ViewHolder holder;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int viewType = getItemViewType(position);
            if (viewType == 0) { // 定位

                convertView = inflater.inflate(R.layout.lacation_item, null);
                RelativeLayout dingwei_rl = (RelativeLayout) convertView.findViewById(R.id.dingwei_rl);
                province = (TextView) convertView.findViewById(R.id.sheng);
                city = (TextView) convertView.findViewById(R.id.shi);
                classify = (TextView) convertView.findViewById(R.id.qu);
                location();
                dingwei_rl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sp = getSharedPreferences("historycity0", Activity.MODE_PRIVATE);
                        if (!Util.isEmpty(cityName)){
                            String s2 = cityName.substring(0, cityName.length() - 1);
                            if (strArray.length < 2) {
                                history = s2 + "," + history;
                            } else {
                                history = s2 + "," + history;
                                int i = history.lastIndexOf(",");
                                history = history.substring(0, i);
                            }
                            Log.e("history", history.toString());
                            SharedPreferences.Editor edit = sp.edit();
                            edit.putString("history", history);
//                        edit.putString("cityname", s2);
                            FileStoreProxy.setValue("cityname", s2);
                            edit.commit();

                            Toast.makeText(CityListActivity.this, s2, Toast.LENGTH_SHORT).show();
                            Intent date = new Intent();
                            date.putExtra("city", s2);
                            setResult(ResultCode.HistoryCode, date);
                            finish();
                        }
                    }
                });

            } else if (viewType == 1) { // 最近访问城市

                convertView = inflater.inflate(R.layout.history_item, null);
                historycityone = (TextView) convertView.findViewById(R.id.historycityone);
                historycitytwo = (TextView) convertView.findViewById(R.id.historycitytwo);
                historycitythree = (TextView) convertView.findViewById(R.id.historycitythree);
                if (history.equals("")) {
                    historycityone.setVisibility(View.GONE);
                    historycitytwo.setVisibility(View.GONE);
                    historycitythree.setVisibility(View.GONE);
                } else {
                    switch (strArray.length) {
                        case 1:
                            historycityone.setVisibility(View.VISIBLE);
                            historycityone.setText(strArray[0]);
                            historycitytwo.setVisibility(View.GONE);
                            historycitythree.setVisibility(View.GONE);
                            break;

                        case 2:
                            historycityone.setVisibility(View.VISIBLE);
                            historycityone.setText(strArray[0]);
                            historycitytwo.setVisibility(View.VISIBLE);
                            historycitytwo.setText(strArray[1]);
                            historycitythree.setVisibility(View.GONE);
                            break;

                        case 3:
                            historycityone.setVisibility(View.VISIBLE);
                            historycityone.setText(strArray[0]);
                            historycitytwo.setVisibility(View.VISIBLE);
                            historycitytwo.setText(strArray[1]);
                            historycitythree.setVisibility(View.VISIBLE);
                            historycitythree.setText(strArray[2]);
                            break;
                    }
                }
                historycityone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String one = historycityone.getText().toString();
                        historyback(one);
                    }
                });
                historycitytwo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String two = historycitytwo.getText().toString();
                        historyback(two);
                    }
                });
                historycitythree.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String three = historycitythree.getText().toString();
                        historyback(three);
                    }
                });

            } else if (viewType == 2) {
                convertView = inflater.inflate(R.layout.recent_city, null);
                GridView hotCity = (GridView) convertView
                        .findViewById(R.id.recent_city);
                hotCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {

                        sp = getSharedPreferences("historycity0", Activity.MODE_PRIVATE);
                        if (strArray.length < 2) {
                            history = city_hot.get(position).getName() + "," + history;
                        } else {
                            history = city_hot.get(position).getName() + "," + history;
                            int i = history.lastIndexOf(",");
                            history = history.substring(0, i);
                        }
                        Log.e("history", history.toString());
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("history", history);
//                        edit.putString("cityname", city_hot.get(position).getName());
                        FileStoreProxy.setValue("cityname", city_hot.get(position).getName());
                        edit.commit();


                        Toast.makeText(CityListActivity.this, city_hot.get(position).getName(), Toast.LENGTH_SHORT).show();
                        Intent date = new Intent();
                        date.putExtra("city", city_hot.get(position).getName());
                        setResult(ResultCode.DetialCode, date);
                        finish();

                    }
                });
                hotCity.setAdapter(new HotCityAdapter(context, this.hotList));
                TextView hotHint = (TextView) convertView.findViewById(R.id.recentHint);
                hotHint.setText("国内热门城市");
            } else if (viewType == 3) {
                convertView = inflater.inflate(R.layout.total_item, null);
            } else {
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.list_item, null);
                    holder = new ViewHolder();
                    holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
                    holder.name = (TextView) convertView
                            .findViewById(R.id.name);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                if (position >= 1) {
                    holder.name.setText(list.get(position).getName());
                    String currentStr = getAlpha(list.get(position).getPinyi());
                    String previewStr = (position - 1) >= 0 ? getAlpha(list
                            .get(position - 1).getPinyi()) : " ";
                    if (!previewStr.equals(currentStr)) {
                        holder.alpha.setVisibility(View.VISIBLE);
                        holder.alpha.setText(currentStr);
                    } else {
                        holder.alpha.setVisibility(View.GONE);
                    }
                }
            }
            return convertView;
        }

        private class ViewHolder {
            TextView alpha; // 首字母标题
            TextView name; // 城市名字
        }
    }

    private void historyback(String s) {

        sp = getSharedPreferences("historycity0", Activity.MODE_PRIVATE);
        if (strArray.length < 2) {
            history = s + "," + history;
        } else {
            history = s + "," + history;
            int i = history.lastIndexOf(",");
            history = history.substring(0, i);
        }
        Log.e("history", history.toString());
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("history", history);
//        edit.putString("cityname", s);
        FileStoreProxy.setValue("cityname", s);
        edit.commit();

        Toast.makeText(CityListActivity.this, s, Toast.LENGTH_SHORT).show();
        Intent date = new Intent();
        date.putExtra("city", s);
        setResult(ResultCode.HistoryCode, date);
        finish();
    }

    class HotCityAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;
        private List<City> hotCitys;

        public HotCityAdapter(Context context, List<City> hotCitys) {
            this.context = context;
            inflater = LayoutInflater.from(this.context);
            this.hotCitys = hotCitys;
        }

        @Override
        public int getCount() {
            return hotCitys.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.item_city, null);
            list_city = (TextView) convertView.findViewById(R.id.city);
            list_city.setText(hotCitys.get(position).getName());
            return convertView;
        }
    }

    class HitCityAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;
        private List<String> hotCitys;

        public HitCityAdapter(Context context, List<String> hotCitys) {
            this.context = context;
            inflater = LayoutInflater.from(this.context);
            this.hotCitys = hotCitys;
        }

        @Override
        public int getCount() {
            return hotCitys.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.item_city, null);
            TextView city = (TextView) convertView.findViewById(R.id.city);
            city.setText(hotCitys.get(position));
            return convertView;
        }
    }

    private boolean mReady;

    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        mReady = true;
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    private boolean isScroll = false;

    private class LetterListViewListener implements MyLetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            isScroll = false;
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s);
                personList.setSelection(position);
                overlay.setText(s);
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 500);
            }
        }
    }

    // 设置overlay不可见
    private class OverlayThread implements Runnable {
        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }
    }

    // 获得汉语拼音首字母
    private String getAlpha(String str) {
        if (str == null) {
            return "#";
        }
        if (str.trim().length() == 0) {
            return "#";
        }
        char c = str.trim().substring(0, 1).charAt(0);
        // 正则表达式，判断首字母是否是英文字母
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c + "").matches()) {
            return (c + "").toUpperCase();
        } else if (str.equals("0")) {
            return "#";
        } else if (str.equals("1")) {
            return "#";
        } else if (str.equals("2")) {
            return "#";
        } else if (str.equals("3")) {
            return "#";
        } else {
            return "#";
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_TOUCH_SCROLL
                || scrollState == SCROLL_STATE_FLING) {
            isScroll = true;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        if (!isScroll) {
            return;
        }

        if (mReady) {
            String text;
            String name = allCity_lists.get(firstVisibleItem).getName();
            String pinyin = allCity_lists.get(firstVisibleItem).getPinyi();
            if (firstVisibleItem < 4) {
                text = name;
            } else {
                text = PingYinUtil.converterToFirstSpell(pinyin)
                        .substring(0, 1).toUpperCase();
            }
            overlay.setText(text);
            overlay.setVisibility(View.VISIBLE);
            handler.removeCallbacks(overlayThread);
            // 延迟一秒后执行，让overlay为不可见
            handler.postDelayed(overlayThread, 1000);
        }
    }


    @Override
    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.top_left_tv:
//                finish();
//                break;
//
//            default:
//                break;
//        }
        if (v.getId() == R.id.top_left_tv){
            finish();
        }
    }
}
